//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;

namespace CommunityServer.Components
{
	/// <summary>
	/// The Ratings class is responsible for storing and retrieving
	/// all ratings from a data store.
	/// </summary>
	public class Ratings
	{
		#region Constructors...
		/// <summary>
		/// Hide default constructor.
		/// </summary>
		private Ratings()
		{
		}
		#endregion

		#region Methods...
		/// <summary>
		/// Stores a rating.
		/// </summary>
		/// <param name="rating">The rating to be stored</param>
		public static void Rate(Rating rating)
		{
			// Don't waste time storing ratings that haven't changed
			if (!rating.HasChanged())
				return;

			// Store rating
			CommonDataProvider.Instance().Rate(rating);
			CSCache.Remove(string.Format("rt:{0}:{1}:{2}", rating.RatingType.ToString(), rating.ItemID.ToString(),rating.User.UserID.ToString()));

			// Fire rating event
			CSEvents.Rate(rating, CSContext.Current.ApplicationType);
		}


		/// <summary>
		/// Retrieves a rating.
		/// </summary>
		/// <param name="type">The type of item that was rated</param>
		/// <param name="itemID">The id of the item that was rated</param>
		/// <param name="userID">The user who rated the item</param>
		/// <returns>The value of the rating</returns>
		public static int GetRating(RatingType type, int itemID, int userID)
		{
            string key = string.Format("rt:{0}:{1}:{2}", type.ToString(), itemID.ToString(),userID.ToString());
            object r = CSCache.Get(key);
            if(r == null)
            {
                int rating =  CommonDataProvider.Instance().GetRating(type, itemID, userID);
                CSCache.MicroInsert(key,rating,3);
                return rating;
            }
            else
            {
                return (int)r;
            }
            
		}


		/// <summary>
		/// Retrieves all ratings for a particular item.
		/// </summary>
		/// <param name="type">The type of item that was rated</param>
		/// <param name="itemID">The id of the item that was rated</param>
		/// <returns>A list of ratings for the item</returns>
		public static IList GetRatings(RatingType type, int itemID)
		{
			return CommonDataProvider.Instance().GetRatings(type, itemID);
		}
		#endregion
	}
}
